//
//  QTZApp.m
//  QTZ
//
//  Created by ski on 2017/7/5.
//  Copyright © 2017年 ski. All rights reserved.
//

#import "JLCFApp.h"

#define kFIRST_INSTALL_SOURCE       @"XSJ_first_source"
#define kFIRST_LAUNCH_VERSION       @"XSJ_first_launch_version"
#define kDEVICE_TOKEN               @"XSJ_devicetoken"
#define kTimeOffset                 @"XSJ_init_timeOffset"

static JLCFApp *qtzApp = nil;

@interface JLCFApp ()<SKStoreProductViewControllerDelegate>
@property(nonatomic, strong) NSString *appName;
@property(nonatomic, strong) NSString *appType;
@property(nonatomic, strong) NSString *appChannel;
@property(nonatomic, assign) NSInteger appVersion;
@property(nonatomic, strong) NSString *appleId;
@property(nonatomic, assign) BOOL firstLaunchInCurrentVersion;
@end

@implementation JLCFApp

+ (JLCFApp *)currentApp
{
    return qtzApp;
}

+ (JLCFApp *)registerApp:(NSString *)appName type:(NSString *)appType channel:(NSString *)appChannel version:(NSInteger)appVersion appleId:(NSString *)appleId
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (appName && appType && appChannel && appVersion > 0 && appleId) {
            if (!qtzApp) {
                qtzApp = [[JLCFApp alloc] init];
                qtzApp.appName = appName;
                qtzApp.appType = appType;
                qtzApp.appChannel = appChannel;
                qtzApp.appVersion = appVersion;
                qtzApp.appleId = appleId;
                
                [qtzApp recordFirstInstallSource];
                [qtzApp recordFirstLaunch];
            }
        }
    });
    return qtzApp;
}

- (NSData *)deviceToken
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kDEVICE_TOKEN];
}

- (void)setDeviceToken:(NSData *)deviceToken
{
    if (deviceToken) {
        [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:kDEVICE_TOKEN];
    }
}

- (void)setServerTime:(NSTimeInterval)serverTime
{
    NSTimeInterval currentInterval = [[NSDate date] timeIntervalSince1970];
    
    currentInterval = floor(currentInterval);
    
    //服务器时间戳减去当前时间戳得到时间offset
    NSTimeInterval timeOffset = serverTime - currentInterval;
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithDouble:timeOffset] forKey:kTimeOffset];
}

- (NSTimeInterval)timeOffset
{
    return [[[NSUserDefaults standardUserDefaults] objectForKey:kTimeOffset] doubleValue];
}

- (NSTimeInterval)correctTime
{
    return [[NSDate date] timeIntervalSince1970] + self.timeOffset;
}

- (NSString *)bundleVersionString
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
}


- (void)updateApp:(BOOL)isToMain Complete:(Complete)Complete
{
    NSString *updateUrl = self.customUpdateUrl;
    if (IsEmptyString(updateUrl)) {
        
        if ( isToMain ) {
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat : @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@&mt=8", MAIN_APPLEID]]];
            
        } else {
            
            SKStoreProductViewController *storeVC = [[SKStoreProductViewController alloc] init];
            storeVC.delegate = self;
            [storeVC loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier: self.appleId}
                               completionBlock:^(BOOL result, NSError *error) {
                                   if (result && !error) {
                                       
                                       if (Complete) {
                                           Complete();
                                       }
                                       
                                       [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:storeVC
                                                                                                                    animated:YES
                                                                                                                  completion:nil];
                                   } else {
                                       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat : @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%@&mt=8", self.appleId]]];
                                       
                                   }
                               }];
            
        }
        
    } else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:updateUrl]];
    }
}


- (void)rateAppWithComplete:(Complete)Complete
{
    __block NSString *rateUrl = [self.customRateUrl copy];
    if (IsEmptyString(rateUrl)) {
        SKStoreProductViewController *storeVC = [[SKStoreProductViewController alloc] init];
        storeVC.delegate = self;
        [storeVC loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier: self.appleId}
                           completionBlock:^(BOOL result, NSError *error) {
                               
                               if (Complete) {
                                   Complete();
                               }
                               
                               if (result && !error) {
                                   [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:storeVC
                                                                                                                animated:YES
                                                                                                              completion:nil];
                               }
                               else
                               {
                                   if (SYSTEM_VERSION >= 7.0) {
                                       rateUrl = [NSString stringWithFormat : @"itms-apps://itunes.apple.com/app/id%@", self.appleId];
                                   }
                                   else
                                   {
                                       rateUrl = [NSString stringWithFormat : @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@", self.appleId];
                                   }
                                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:rateUrl]];
                               }
                           }];
    }
    else
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:rateUrl]];
    }
}


- (BOOL)checkUpdate
{
    return self.latestVersion > self.appVersion;
}

- (NSString *)appSource
{
    return [NSString stringWithFormat:@"%@%ld", self.appChannel, (long)self.appVersion];
}

- (NSString *)firstInstallSource
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kFIRST_INSTALL_SOURCE];
}

- (void)recordFirstInstallSource {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *firstSource = [userDefault objectForKey:kFIRST_INSTALL_SOURCE];
    
    if (!firstSource) {
        [userDefault setObject:self.appSource forKey:kFIRST_INSTALL_SOURCE];
    }
}

- (void)recordFirstLaunch {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *firstLauchString = [userDefault objectForKey:kFIRST_LAUNCH_VERSION];
    
    if (!firstLauchString || ![firstLauchString isEqualToString:self.bundleVersionString]) {
        self.firstLaunchInCurrentVersion = YES;
        [userDefault setObject:self.bundleVersionString forKey:kFIRST_LAUNCH_VERSION];
    }
}

//- (UIRemoteNotificationType)pushStatus
//{
//    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
//        UIRemoteNotificationType remoteType;
//        if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
//            remoteType = (UIRemoteNotificationType)[[UIApplication sharedApplication] currentUserNotificationSettings].types;
//        } else {
//            remoteType = (UIRemoteNotificationType)UIUserNotificationTypeNone;
//        }
//        return remoteType;
//    } else {
//        return [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
//    }
//}

#pragma mark - SKStoreProductViewControllerDelegate
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
{
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

@end
